<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Sale\Controllers;

use App\Eloquent\Ygt\Company;
use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\CustomerOrder;
use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\SaleCompany;
use App\Eloquent\Ygt\SaleCompanyRelation;
use App\Eloquent\Ygt\DepartmentUser;
use App\Engine\Buyers;
use App\Engine\Func;
use App\Engine\OrderType;
use Framework\BaseClass\Api\Controller;

class CompanyController extends Controller
{
    public $saleId      = 241;
    public function index()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $title              = request('keyword','');
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        if($title=='')
        {
            return ['message'=>'该厂不存在','lists'=>[]];
        }
        $where              = [];
        $where['title']     =['like','%'.$title.'%'];
        $fields             = 'id,title';
        $collection         = Company::getList($where,$fields);
        $lists              = $collection->toArray();
        $size               = count($lists);
        if($size==1){
            return ['message'=>'','lists'=>$lists];
        }else{
            return ['message'=>'该厂不存在','lists'=>[]];
        }
    }
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $title              = request('keyword','');
        if( !$userInfo ){
            xThrow( ERR_PARAMETER );
        }
        $where              = [ 'user_id'=>$userId, ];
        if($title)
        {
            $where['title'] = $title;
        }
        $collection         = Customer::getCompanyList($where);
        $letterArr          = $collection->pluck('first_letter')->all();
        $lists              = [];
        if($letterArr)
        {
            $letterArr      = array_unique($letterArr);
            sort($letterArr);
            foreach($collection as $key=>$val)
            {
                ////添加数据
                //获取客户ID
                $customerRow = \App\Eloquent\Ygt\Customer::where(['company_id'=>$val['id'],'user_id'=>$userId])->first();
                if($customerRow){
                    $customerId             = $customerRow->id;
                }else{
                    $customerId             = 0;
                }

                //应收款
                $where                  = [
                    ['customer_id','=',$customerId],
                    ['status','=',0]
                ];
                $totalMoney             = \App\Eloquent\Ygt\WarehouseBill::where($where)->sum('now_money');
                $totalMoneyTxt          = $totalMoney!= 0 ? '¥ '.$totalMoney : '无';
                //最近收款
                $where                  = [
                    ['customer_id','=',$customerId],
                    ['table','=','warehouse_bill'],
                ];
                $lastMoney              = \App\Eloquent\Ygt\BillLog::where($where)->value('money');
                $lastMoneyTxt           = $lastMoney!= 0 ? '¥ '.$lastMoney : '无';
                $where                = ['customer_name'=>$customerId];
                $lastOrder            = CustomerOrder::where($where)->orderByDesc('id')->first();
                $lastOrderTxt        = '无';
                if($lastOrder)
                {
                    $lastOrderArr       = $lastOrder->toArray();
                    $createdAt          = $lastOrderArr['created_at'];
                    $productNum         = $lastOrderArr['product_num'];
                    $productNumArr      = explode(',',$productNum);
                    $productNumStr      = '';
                    if( is_array($productNumArr) && !empty($productNumArr[0]))
                    {
                        $productNumStr  = $productNumArr[0].$productNumArr[1];
                    }
                    $lastOrderTxt      = date('Y-m-d',$createdAt);
                    $lastOrderTxt      .= ' '.$productNumStr;
                }


                $collection[$key]->last_order   = $lastOrderTxt;
                $collection[$key]->last_money   = $lastMoneyTxt;
                $collection[$key]->total_money  = $totalMoneyTxt;
                $collection[$key]->avatars_url  = '';
            }
            $listArr            = $collection->groupBy('first_letter')->toArray();
            foreach($letterArr as $key=>$val)
            {
                $lists[$key]['letter']      = $val;
                $lists[$key]['list']       = $listArr[$val];
            }
        }
        return $lists;
    }
    public function add()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $id                 = request('id',0);
        $companyId          = intval($id);
        if( !$userInfo || !$companyId)
        {
            xThrow( ERR_PARAMETER );
        }
        $userCompanyId      = $userInfo->company_id;
        if($userCompanyId == $companyId)
        {
            xThrow( ERR_PARAMETER,'你是该厂员工不能添加该厂' );
        }
        //检测是否添加了该厂
        $where              = [
            'user_id'=>$userId,
            'company_id'=>$companyId,
        ];
        $relationInfo       = Customer::getInfo($where);
        if($relationInfo)
        {
            xThrow( ERR_PARAMETER,'已经添加过了' );
        }
        //插入客户表
        $where              = ['user_id'=>$userId];
        $customer           = Customer::getInfo($where);
        if(!$customer)
        {
            xThrow( ERR_PARAMETER,'客户信息出错' );
        }
        $data               = $customer->toArray();
        unset($data['created_at']);
        unset($data['updated_at']);
        unset($data['add_user_id']);
        $data['company_id'] = $companyId;
        $customerId         = Customer::insertOneData($data,'id');
        if(!$customerId)
        {
            xThrow(ERR_UNKNOWN);
        }
        $result             = ['message'=>'添加成功'];
        return $result;
    }
    public function confirm()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $saleCompanyId      = request('sale_company_id',0);
        if( !$userInfo || !$saleCompanyId){
            xThrow( ERR_PARAMETER );
        }
        $where              = ['user_id'=>$userId];
        $customer           = Customer::getInfo($where);
        $customerId         = $customer->id;
        $relationData       = ['user_id'=>$userId,'sale_company_id'=>$saleCompanyId,'customer_id'=>$customerId];
        $existData          = SaleCompanyRelation::getList($relationData);
        $existDataResult    = $existData->isEmpty();
        if($existDataResult){
            $relationResult     = SaleCompanyRelation::insertOneData($relationData);
            if($relationResult === false)
            {
                xThrow(ERR_UNKNOWN);
            }
            $result             = ['message'=>'添加成功'];
        }else{
            $result             = ['message'=>'已经添加过了'];
        }
        return $result;
    }
    public function detail()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $saleCompanyId      = request('id',0);
        if(!$userInfo || !$saleCompanyId)
        {
            xThrow( ERR_PARAMETER );
        }
        $where              = ['id'=>$saleCompanyId];
        $collection         = SaleCompany::getInfo($where);

        $where          = ['company_id'=>$saleCompanyId,'user_id'=>$userId];
        $fields         = 'id,customer_name';
        $customer       = Customer::getInfo($where,$fields);

        if($collection && $customer){
            $info           = $collection->toArray();
            $fieldsTempArr  = [
                'customer_name'=>'','company_name'=>'','company_ids'=>'',
                'first_letter'=>'','customer_no'=>'','avatars_id'=>'',
                'avatars_url'=>'','customer_level'=>'','customer_level_title'=>'',
                'customer_tel'=>'','customer_address'=>'','contact_person'=>'',
                'contact_phone'=>'','contact_address'=>'','sales_name'=>'',
                'sales_uid'=>'','merchandiser_uid'=>'','merchandiser_name'=>'',
                'province_id'=>'','city_id'=>'','area_id'=>'',
                'province_name'=>'','city_name'=>'','area_name'=>'',
                'reg_mobile'=>'','last_order_time'=>'','total_money'=>'',
                'last_money'=>'','last_order'=>'','remind'=>[],
                'customer_detail_address'=>'','buyerList'=>[],
            ];
            $customerId     = $customer->id;
            $customerName   = $customer->customer_name;
            $info           = array_merge($fieldsTempArr,$info);
            $info['customer_id']    = $customerId;
            $info['customer_name']  = $customerName;
            return $info;
        }else{
            xThrow(ERR_UNKNOWN);
        }
    }
    //创建订单第一步，提供默认值
    public function orderFirst()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $companyId          = request('company_id',0);
        $companyName        = Company::getOneValueById($companyId, 'title');
        $where              = ['user_id'=>$userId];
        $customer           = Customer::getInfo($where);
        if(!$userId || !$customer)
        {
            xThrow(ERR_UNKNOWN);
        }
        $customerId         = $customer->id;
        $result             = [
            'company_id'=>$companyId, 'company_name'=>$companyName,'customer_id'=>$customerId
        ];
        return $result;
    }
    /**
     * @return array
     * 客户订单列表
     */
    public function orderList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $companyId          = request('company_id',0);
        $customerId          = request('customer_id',0);
        $where              = ['company_id'=>$companyId,'user_id'=>$userId];
        $customer           = Customer::getInfo($where);
        if(!$userId || !$companyId || !$customer)
        {
            xThrow(ERR_UNKNOWN);
        }
        if(!$customerId){
            $customerId         = $customer->id;
        }
        $isAddOrder         = $customer->is_add_order;

        $where  = [];
        $where['company_id'] = $companyId;
        $where['customer_name'] = $customerId;

        $customerOrderList = CustomerOrder::where($where)->orderby('updated_at', 'desc')->get();


        $tmpOrderList = [];
        foreach ($customerOrderList as $tmpCustomerOrderRow) {
            //订单字段处理
            $tmpCustomerOrderRow = \App\Engine\OrderEngine::dealOrderFiled($tmpCustomerOrderRow);

            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpCustomerOrderRow['production_case_diagram']) ? $tmpCustomerOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            //订单创建时间（派发时间）
            $orderCreateTime = $tmpCustomerOrderRow['order_create_time'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
                if ($orderCreateTime < 631152000) {//过滤1970的情况
                    $orderCreateTime = '';
                }
            } else {
                $orderCreateTime = '';
            }



            //订单状态
            $userId = Func::getHeaderValueByName('userid');
            $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
            $isManager = \App\Eloquent\Ygt\Privilege::getAppnodeId($userInfo['privilege_id'], 1);//是否为下单人（管理员权限）


			$statusColor    = 'FE7E57';//默认颜色
            if(!$tmpCustomerOrderRow['is_deal_price']){
                //订单价格未确认
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$tmpCustomerOrderRow['id']])->first();
                if($customerOrderPriceObj){
                    $customerOrderPriceStatus = $customerOrderPriceObj->status;

                    //如果是客商，在下单人报价时状态始终不变
//                    $userId = Func::getHeaderValueByName('userid');
                    $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
                    if($userInfo['company_id'] == 2 && $userInfo['privilege_id'] == 110){
                        if(in_array($customerOrderPriceStatus,[2,3])){
                            $customerOrderPriceStatus = 1;
                        }
                    }


                    $customerOrderPriceStatusArr = config('order.customer_order_price_status_list');
                    if(isset($customerOrderPriceStatusArr[$customerOrderPriceStatus])){
                        $orderStatus = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['txt'];
						$statusColor    = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['color'];
                    }else{
                        $orderStatus = '';
                    }
                    $type = 2;
                }else{
                    $orderStatus = '';
                    $type = 1;
                }
            }else{
                //订单价格已确认
                $customerOrderStatusList = config('order.customer_order_status_list');
				if(isset($customerOrderStatusList[$tmpCustomerOrderRow['status']])){
						$orderStatus = $customerOrderStatusList[$tmpCustomerOrderRow['status']]['txt'];
						$statusColor = $customerOrderStatusList[$tmpCustomerOrderRow['status']]['color'];
				}

                $type = 1;

//                if(!$isManager){
//                    $type = 2;
//                }
            }


            //获取工序类型名称
            $orderTypeTitle = OrderType::getOneValueById($tmpCustomerOrderRow['order_type'], 'title');

            $tmpCustomerOrderRow['order_title'] = \App\Engine\Common::changeSnCode($tmpCustomerOrderRow['order_title']);
            $tmpOrderList[] = [
                '$customer_title' => '单位名称',//工单列表展示字段
                '$product_title' => '品名',//工单列表展示字段
                '$order_title' => '单号',//工单列表展示字段
                '$customer_name' => isset($tmpCustomerOrderRow['field_name_23']) ? $tmpCustomerOrderRow['field_name_23'] : '',//新加字段客户
                '$product_name' => isset($tmpCustomerOrderRow['product_name']) ? $tmpCustomerOrderRow['product_name'] : '',//新加字段品名
                '$order_title_value' => $tmpCustomerOrderRow['order_title'],//新加字段单号
                '$firstPropertyName' => '成品规格',
                '$secondPropertyName' => '数量',
                '$thirdPropertyName' => '交货日期',
                '$thirdPropertyValue' => $tmpCustomerOrderRow['finished_date'],
                '$secondPropertyValue' => $tmpCustomerOrderRow['product_num'],
                '$firstPropertyValue' => isset($tmpCustomerOrderRow['finished_specification']) ? $tmpCustomerOrderRow['finished_specification'] : '',
                '$productionCaseDiagram' => $productionCaseDiagram,
                '$productOrderTimeValue' => $orderCreateTime,
                '$orderTypeTitle' => $orderTypeTitle,
                '$orderNumberValue' => $orderTypeTitle,
                '$orderTimeValue' => $tmpCustomerOrderRow['finished_date'],
                '$relate_id' => $tmpCustomerOrderRow['id'],
                '$orderStatus' => $orderStatus,
                '$statusColor' => $statusColor,
                'type' => $type,
            ];
        }

        $orderList = $tmpOrderList;

        $re['is_add_order'] = $isAddOrder;
        $re['pageID'] = 0;
        $re['data']['$tableviewSource'] = $orderList;

        return $re;
    }
    public function search()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if( !$userInfo ){
            xThrow( ERR_PARAMETER );
        }
        $title              = request('keyword','');
        if($title == '')
        {
            return [];
        }
        $where              = ['title'=>['like','%'.$title.'%']];
        $fields             = '';
        $collection         = SaleCompany::getList($where,$fields);
        $lists              = $collection->toArray();
        return $lists;
    }
    public function del()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->saleId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $saleCompanyId      = request('id',0);
        if(!$userInfo || !$saleCompanyId)
        {
            xThrow( ERR_PARAMETER );
        }
        $where              = ['sale_company_id'=>$saleCompanyId];
        $delResult          = SaleCompanyRelation::del($where);
        if($delResult===false)
        {
            xThrow(ERR_UNKNOWN);
        }
        return ['message'=>'删除成功'];
    }
}